#include"transferfile.h"

//********************************************************************************
//接收指令函数
//********************************************************************************
task_t* recvCmd(int peerfd)
{
	task_t* ptask = (task_t*)calloc(1,sizeof(task_t));//calloc同时也进行了初始化操作

	ptask->peerfd = peerfd;

	//先接收指令类型;
	recvCircle(peerfd,(char*)&ptask->type,4);

	printf("指令类型为：%d\n",ptask->type);

    //再接收指令参数
	if(ptask->type == CMD_TYPE_PUT || ptask->type == CMD_TYPE_GET)
	{
		//先接文件名长度
		int filelength = 0;
		recvCircle(peerfd,(char*)&filelength,4);
		//在接收文件名
		recvCircle(peerfd,ptask->data,filelength);
	}
	else
	{
		//接收参数
		recvCircle(peerfd,ptask->data,100);
	}

	printf("ptask->data = %s\n",ptask->data);
	return ptask;
}

//********************************************************************************
//接收信息函数，接收length长度信息到buff
//********************************************************************************
int recvCircle(int fd, char * buff, int length)
{
	char * pbuf = buff;
	int left = length;
	int ret = 0;
	while(left > 0) {
		ret = recv(fd, pbuf, left, 0);
		if(0 == ret) {
			close(fd);
			break;
		} else if(ret == -1 && errno == EINTR) {
			continue;
		} else if(ret == -1) {
			perror("recv");
			break;
		} else {// > 0
			pbuf += ret;
			left -= ret;
		}
	}
	return length - left;
}